
import 'package:flutter_blue/flutter_blue.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'log_util.dart';

class BleManager{

  static int mtu = 0;

  static Future<void> startScan()async {
    FlutterBlue.instance.isScanning.first.then((value) {
      Log.d("是否正在扫描中:$value");
      if(!value) {
        FlutterBlue.instance.startScan(timeout: const Duration(seconds: 10));
      }else {
        Fluttertoast.showToast(msg: '正在扫描中，请稍后...');
      }
    });
  }

  static void stopScan(){
    FlutterBlue.instance.stopScan();
  }

  static Future<List<BluetoothDevice>> getConnectedDevices(){
    return FlutterBlue.instance.connectedDevices;
  }

  static Stream<List<ScanResult>> getScanResults(){
    return FlutterBlue.instance.scanResults;
  }

  static Stream<BluetoothState> getState(){
    return FlutterBlue.instance.state;
  }

  static Stream<bool> isScanning(){
    return FlutterBlue.instance.isScanning;
  }

  static Future<void> connect(BluetoothDevice device) async {
    return device.connect(timeout: const Duration(seconds: 8), autoConnect: false);
  }

  static Future<void> disconnect(BluetoothDevice device){
    return device.disconnect();
  }

  // static void requestMtu(BluetoothDevice device, int reqMtu){
  //   device.requestMtu(mtu).then((value) {
  //     Log.d('申请到的mtu大小为$reqMtu');
  //     mtu = reqMtu;
  //   }).onError((error, stackTrace) {
  //     Log.d('申请mtu大小$reqMtu报错，错误为$error');
  //     requestMtu(device, reqMtu ~/ 2);
  //   });
  // }

  static Future<List<BluetoothService>> discoverServices(BluetoothDevice device){

    return device.discoverServices();
  }

  static Future<void> createBond(BluetoothDevice device){
    return device.pairWithDevice();
  }
}